import random
import time
import ssl
import json  # 导入 JSON 模块

from paho.mqtt import client as mqtt_client


broker = 'n12ebcd2.ala.cn-hangzhou.emqxsl.cn'
port = 8883
topic = "message"
client_id = f'python-mqtt-{random.randint(0, 1000)}'
username = 'emqx'
password = '123456'

# 连接
def connect_mqtt():
    def on_connect(client, userdata, flags, rc):
        if rc == 0:
            print("Connected to MQTT Broker!")
        else:
            print("Failed to connect, return code %d\n", rc)

    client = mqtt_client.Client(client_id)
    client.username_pw_set(username, password)
    client.on_connect = on_connect
    # 启用 TLS/SSL 加密
    client.tls_set(certfile=None, keyfile=None, cert_reqs=ssl.CERT_NONE, tls_version=ssl.PROTOCOL_TLSv1_2)
    client.connect(broker, port)
    return client

# 发布信息
def publish(client):
    msg_count = 0
    while True:
        time.sleep(1)
        # msg = f"messages: {msg_count}"
        msg = json.dumps({"lon": 113.37810517, "lat": 23.05565750, "msl": "23M", "beijing_time_str": "12:00:00"})  # 转换为 JSON 格式

        result = client.publish(topic, msg)
        # result: [0, 1]
        status = result[0]
        if status == 0:
            print(f"Send `{msg}` to topic `{topic}`")
        else:
            print(f"Failed to send message to topic {topic}")
        msg_count += 1


def run():
    client = connect_mqtt()
    client.loop_start()
    publish(client)


if __name__ == '__main__':
    run()